import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';

import {Subject} from "rxjs/Subject";
import {Observable} from 'rxjs';

import {ClientModel} from "../../../model/pages/client/client-list/client.model";
import {ClientGroupModel} from "../../../model/pages/client/client-list/client-group.model";
import {ClientIndividualProvider} from "../client-individual/client-individual.provider";
import {ClientProspectiveProvider} from "../client-prospective/client-prospective.provider";
import {ClientGender} from "../../../model/pages/client/client-list/contact-item";
import {PinyinService} from "../../../services/common/pinyin.service";


@Injectable()
export class ClientListProvider {
    //pouchDB文档id
    // public dbDocId = 'client-groups-data';
    //pouchDB数据库名
    // public dbName = 'client-db';
    //pouchDB客户分组数据key
    // public dataKey = 'clientGroups';

    //获取客户列表数据的可观察对象
    public subject: Subject<Array<ClientGroupModel>>;

    pinyin;

    constructor(public http: HttpClient,
                public indevidualProvider?: ClientIndividualProvider,
                public prospectiveProvider?: ClientProspectiveProvider,) {

        //todo :可能会改！
        // localStorageService.initialize(this.dbName);
        this.subject = new Subject<Array<ClientGroupModel>>();

        this.pinyin = PinyinService.generate();
    }

    setClientNamePinyin(clientList) {
        clientList.forEach(client => {
            client.nameFirstAlpha = "";
            const pinyinAl = this.pinyin.getFullChars(client.name);
            if (pinyinAl) {
                client.nameFirstAlpha = pinyinAl[0].toUpperCase();
                client.fullPinyin = pinyinAl;
            }
        });
    }

    /**
     * 获取服务器客户列表数据
     * @param {string} keyWord
     * @returns {Observable<any>}
     */
    public getClientsFromServer(keyWord?: string): Observable<any> {
        return Observable.create(ob0 => {
            this.indevidualProvider.getIndividualAll(keyWord).subscribe(d => {
                this.pinyin.setOptions({checkPolyphone: false, charCase: 0});
                this.setClientNamePinyin(d);
                this.prospectiveProvider.getAllProspect(keyWord).subscribe(pro => {
                    if (pro && pro.length) {
                        this.setClientNamePinyin(pro);
                    }
                    const uniqueLeadList = this.uniqueClient(d, pro);
                    ob0.next({
                        clientList: d,
                        leadList: uniqueLeadList
                    });
                }, error => {
                    ob0.next(error);
                });
            }, error2 => {
                ob0.next(error2);
            });
        });
    }


    /**
     * 合并准客户到核心客户
     * @param clientList 核心客户列表
     * @param leadList 准客户列表
     */
    public uniqueClient(clientList, leadList) {

        const uniqueLeadList = [];
        const combineClientId = [];
        leadList.forEach(leadClient => {
            //核心客户与准客户姓名相等

            let clientListNameEqual = clientList.filter(client => {
                return client.name === leadClient.name;
            });

            // let client = null;
            // for(let i = 0,len = clientList.length; i < len; i++){
            //     if(leadClient.name === clientList[i].name){
            //         client = clientList[i];
            //         break;
            //     }
            // }

            //核心客户与准客户存在相等的电话号码
            let mobileEqual = false,
                clientG = {clientId: ''};
            if (clientListNameEqual && clientListNameEqual.length) {

                clientListNameEqual.forEach(client => {
                    client.mobilePhone.forEach(cMobile => {
                        let cMobileNo = cMobile.mobile;
                        leadClient.mobileList.forEach(lMobileNo => {
                            if (cMobileNo == lMobileNo) {
                                mobileEqual = true;
                                clientG = client;
                            }
                        });
                    });
                });
            }

            if (mobileEqual) {
                combineClientId.push({
                    clientId: clientG.clientId,
                    leadId: leadClient.leadId
                });
            } else {
                uniqueLeadList.push(leadClient);
            }
        });

        this.combineLeadClient(combineClientId);

        return uniqueLeadList;
    }

    /**
     * 请求合并已经成为核心客户的准客户
     * @param combineClientIdList
     */
    public combineLeadClient(combineClientIdList) {
        if (combineClientIdList && combineClientIdList.length) {
            return this.http.post(
                `/leads/v1/leads/uniqueWithCoreClient`,
                combineClientIdList,
                {responseType: "text"}).subscribe(() => {
                console.log('combine success!');
            })
        }
    }

    public getClientGroupList(keyWord?: string) {
        return this.getClientsFromServer(keyWord).map(data => {
            return this.groupingFlat(data.clientList.concat(data.leadList));
        });
    }

    //客户按名字拼音扁平化分组
    public groupingFlat(clientList) {
        let contactItemList = [];
        const gAlphabets = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#'.split('');
        gAlphabets.forEach(a => {

            const currentGroupClients = clientList.filter(client => client.nameFirstAlpha === a);
            const foundTotal = currentGroupClients.length;
            if (foundTotal) {
                const group = {
                    groupName: a,
                    total: foundTotal
                };
                contactItemList.push(group);

                //region 分离客户名称中文开头与非中文开头;
                const zhcnClients = [];
                const noneZhcnClients = [];
                let nameWordClientGroup = [];
                currentGroupClients.forEach(client => {
                    let gender = '';
                    if (client.sex == 1 || client.sex == 'M') {
                        gender = 'M';
                    } else if (client.sex == 'F' || client.sex == 2) {
                        gender = 'F';
                    }
                    //判断客户姓名是否中文开头;
                    const firstIsZhcn = /.*[\u4e00-\u9fa5]+.*$/.test(client.name[0]);
                    const clientFilter = {
                        id: client.clientId ? client.clientId : client.leadId,
                        clientId: client.clientId,
                        leadId: client.leadId,
                        clientType: client.clientType,
                        name: client.name,
                        nameFirstAlpha: client.nameFirstAlpha,
                        gender: gender,
                        vipFlag: client.vipFlag,
                        vipFlagDesc: client.vipFlagDesc,
                        clientRole: client.clientRole,
                        fullPinyin: client.fullPinyin,
                    };
                    if (firstIsZhcn) {
                        zhcnClients.push(clientFilter);
                    } else {
                        noneZhcnClients.push(clientFilter);
                    }
                });
                //endregion

                if (zhcnClients.length) {
                    let nameOfFirst = {};
                    zhcnClients.forEach(zhClient => {
                        let firstName = zhClient.name[0];
                        nameOfFirst[firstName] = firstName;
                    });
                    let nameOfFirstArray = [];
                    for (let k in nameOfFirst) {
                        const pinyinAl = this.pinyin.getFullChars(k);
                        nameOfFirstArray.push({
                            pinyin: pinyinAl,
                            word: k
                        });
                    }
                    nameOfFirstArray.sort((a, b) => {
                        return a.pinyin.localeCompare(b.pinyin);
                    });
                    nameOfFirstArray.forEach(o => {
                        let clientLi = [];
                        zhcnClients.forEach(zhcnClient => {
                            if (o.word == zhcnClient.name[0]) {
                                clientLi.push(zhcnClient);
                            }
                        });
                        clientLi.sort((a, b) => {
                            return a.fullPinyin.localeCompare(b.fullPinyin);
                        });
                        nameWordClientGroup = nameWordClientGroup.concat(clientLi);
                    });

                }
                if (noneZhcnClients.length) {
                    noneZhcnClients.sort((a, b) => {
                        return a.fullPinyin.localeCompare(b.fullPinyin);
                    });
                }
                contactItemList = contactItemList.concat(nameWordClientGroup.concat(noneZhcnClients));

            }

        });
        const noneGroup = {
            groupName: gAlphabets[gAlphabets.length - 1],
            total: 0
        };
        const noneGroupTotal = clientList.filter(c => {
            const foundTotal = gAlphabets.filter(gA => gA === c.nameFirstAlpha).length;
            return !foundTotal;
        }).length;
        if (noneGroupTotal > 0) {
            contactItemList.push(noneGroup);
        }
        clientList.forEach(c => {
            let found = false;
            gAlphabets.forEach(a => {
                if (c.nameFirstAlpha === a) {
                    found = true;
                }
            });
            if (!found) {
                noneGroup.total++;
                let gender = '';
                if (c.sex == 1 || c.sex == 'M') {
                    gender = 'M';
                } else if (c.sex == 'F' || c.sex == 2) {
                    gender = 'F';
                }
                contactItemList.push({
                    id: c.clientId ? c.clientId : c.leadId,
                    clientId: c.clientId,
                    leadId: c.leadId,
                    clientType: c.clientType,
                    name: c.name,
                    nameFirstAlpha: c.namePinyin,
                    gender: gender,
                    vipLevel: c.vipFlag
                });
            }
        });
        return contactItemList;
    }

    //用于手机通讯录导入 客户按名字拼音扁平化分组
    public importPhoneGroupingFlat(clientList) {
        let contactItemList = [];
        this.setClientNamePinyin(clientList);//为姓名添加拼音
        const gAlphabets = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#'.split('');
        gAlphabets.forEach(a => {

            const foundTotal = clientList.filter(client => client.nameFirstAlpha === a).length;
            if (foundTotal) {
                const group = {
                    groupName: a,
                    total: 0
                };
                contactItemList.push(group);

                //分离客户名称中文开头与非中文开头;
                const zhcnClients = [];
                const noneZhcnClients = [];
                let nameWordClientGroup = [];
                clientList.forEach(client => {
                    if (client.nameFirstAlpha === a) {
                        group.total++;
                        //判断客户姓名是否中文开头;
                        const firstIsZhcn = /.*[\u4e00-\u9fa5]+.*$/.test(client.name[0]);
                        const clientFilter = {
                            name: client.name,
                            phone: client.phone
                        };
                        if (firstIsZhcn) {
                            zhcnClients.push(clientFilter);
                        } else {
                            noneZhcnClients.push(clientFilter);
                        }
                    }
                });
                if (zhcnClients.length) {
                    let nameOfFirst = {};
                    zhcnClients.forEach(zhClient => {
                        let firstName = zhClient.name[0];
                        nameOfFirst[firstName] = firstName;
                    });
                    let nameOfFirstArray = [];
                    for (let k in nameOfFirst) {
                        const pinyinAl = this.pinyin.getFullChars(k);
                        nameOfFirstArray.push({
                            pinyin: pinyinAl,
                            word: k
                        });
                    }
                    nameOfFirstArray.sort((a, b) => {
                        if (a.pinyin && b.pinyin) {
                            return a.pinyin.localeCompare(b.pinyin);
                        }
                    });

                    nameOfFirstArray.forEach(o => {
                        let clientLi = [];
                        zhcnClients.forEach(zhcnClient => {
                            if (o.word == zhcnClient.name[0]) {
                                clientLi.push(zhcnClient);
                            } else {
                            }
                        });
                        clientLi.sort((a, b) => {
                            if (a.fullPinyin && b.fullPinyin) {
                                return a.fullPinyin.localeCompare(b.fullPinyin);
                            }
                        });
                        nameWordClientGroup = nameWordClientGroup.concat(clientLi);
                    });

                }
                if (noneZhcnClients.length) {
                    noneZhcnClients.sort((a, b) => {
                        if (a.fullPinyin && b.fullPinyin) {
                            return a.fullPinyin.localeCompare(b.fullPinyin);
                        }
                    });
                }
                contactItemList = contactItemList.concat(nameWordClientGroup.concat(noneZhcnClients));

            }

        });
        const noneGroup = {
            groupName: gAlphabets[gAlphabets.length - 1],
            total: 0
        };
        const noneGroupTotal = clientList.filter(c => {
            const foundTotal = gAlphabets.filter(gA => gA === c.nameFirstAlpha).length;
            return !foundTotal;
        }).length;
        if (noneGroupTotal > 0) {
            contactItemList.push(noneGroup);
        }
        clientList.forEach(c => {
            let found = false;
            gAlphabets.forEach(a => {
                if (c.nameFirstAlpha === a) {
                    found = true;
                }
            });
            if (!found) {
                noneGroup.total++;
                contactItemList.push({
                    id: c.id,
                    name: c.name,
                    phone: c.phone
                });
            }
        });
        return contactItemList;
    }

    /**
     * 获取客户头像
     * @param {ClientModel} client
     * @returns {string}
     */
    public getClientAvatar(client): string {
        if (!client) return './assets/images/client/client-list/icon_contact_unknown.png';
        if (client.avatar) return client.avatar;

        const gender = client.gender;
        if (gender === 'M' || gender === ClientGender.Male) {
            return './assets/images/client/client-list/icon_contact_man.png';
        } else if (gender === "F" || gender === ClientGender.Female) {
            return './assets/images/client/client-list/icon_contact_woman.png';
        } else {
            return './assets/images/client/client-list/icon_contact_unknown.png';
        }
    }

    public vw(v: number) {
        const w = window['innerWidth'];
        return Number((v * w / 100).toFixed(5));
    }

    public vh(v: number) {
        const h = window['innerHeight'];
        return Number((v * h / 100).toFixed(5));
    }

}


